package com.ale.oxetool.util;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class SSHUtil {
    private static final String ENCODING = "UTF-8";
    private static Logger log = LoggerFactory.getLogger(SSHUtil.class);

    private static Session getJSchSession(String username, String password, String host, int port) throws JSchException {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, host, port);
        session.setPassword(password);
        // Never ask to enter "yes" on the first time.
        session.setConfig("StrictHostKeyChecking", "no");
//        session.setTimeout();
        session.connect();
        return session;
    }

    public static String execCommandByShell(Session session,
                                            String command, String resultEncoding) throws IOException, JSchException {
        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        channelExec.setCommand(command);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        String result = IOUtils.toString( channelExec.getInputStream(), resultEncoding);
        channelExec.disconnect();
        return result;
    }



//    public static void main(String[] args) throws JSchException, IOException, InterruptedException {
//        long lastStamp = System.currentTimeMillis();
////
//        Session session = getJSchSession("mtcl", "mtcl", "151.1.1.15", 22);
//        log.info("Get session used {} ms", System.currentTimeMillis() - lastStamp);
//        String cmd = "ls /";
//        cmd= "tool ippstat list 19 1";
//        cmd = String.format("tool ippstat telnet d %s t %d\n", "31002", 1440);
//
//        String result = execCommandByShell(session, cmd, ENCODING);
//        log.info("result: {}", result);
//        session.disconnect();
//    }
}
